package com.my.controller;

import com.my.domain.dto.Column;
import com.my.domain.dto.Table;
import com.my.domain.vo.BaseResponseVo;
import com.my.domain.vo.DbVo;
import com.my.domain.vo.RequestVo;
import com.my.service.DbService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;

import java.util.Map;

import static com.my.util.DB.getInstance;

/**
 * Created by Administrator on 2017/6/12.
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private DbService dbService;

    @RequestMapping(method = RequestMethod.GET)
    public BaseResponseVo getDbResult(@Validated RequestVo httpRequest) throws Exception{
        // 获取第一个数据库中表及表中的字段的属性
        String firstUrl = getInstance().appendMysqlUrl(httpRequest.getFirstDbHost(), httpRequest.getFirstDbName());
        Connection connectionFirst = getInstance().buildDbConnection(firstUrl, httpRequest.getFirstDbUsername(), httpRequest.getFirstDbPassword());
        Map<String, Table> tableFirstMap = getInstance().getTables(connectionFirst, httpRequest.getFirstDbName());
        for (Map.Entry entry : tableFirstMap.entrySet()) {
            Map<String, Column> columnFirstMap = getInstance().getTableColumns(connectionFirst, httpRequest.getFirstDbName(), (String)entry.getKey());
            ((Table)entry.getValue()).setColumnMap(columnFirstMap);
        }
        //关闭连接
        getInstance().closeDbConnection();
        // 获取第二个数据库中表及表中的字段的属性
        String secondUrl = getInstance().appendMysqlUrl(httpRequest.getSecondDbHost(), httpRequest.getSecondDbName());
        Connection connection = getInstance().buildDbConnection(secondUrl, httpRequest.getSecondDbUsername(), httpRequest.getSecondDbPassword());
        Map<String, Table> tableSecondMap = getInstance().getTables(connection, httpRequest.getSecondDbName());

        for (Map.Entry entry : tableSecondMap.entrySet()) {
            Map<String, Column> columnSecondMap = getInstance().getTableColumns(connection, httpRequest.getSecondDbName(), (String)entry.getKey());
            ((Table)entry.getValue()).setColumnMap(columnSecondMap);
        }
        //关闭连接
        getInstance().closeDbConnection();
        // 获取比较结果
        StringBuilder [] stringBuilders = dbService.compare(httpRequest.getFirstDbName(), httpRequest.getSecondDbName(), tableFirstMap,tableSecondMap);
        // 返回比较结果
        DbVo dbVo = new DbVo();
        dbVo.setStr(stringBuilders);
        return  dbVo;

    }
}
